package user

import (
	"chaowan/data_source"
	"chaowan/models"
	"chaowan/utils"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/alipay"
	"github.com/go-pay/xlog"
	"math/rand"
	"net/http"
	"time"
)

const (
	appidzfb     = "2021004170636001"
	yygongyao    = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgz8rRGFcmvRZ8MZZv4txBramqyeUjGD4WCNMQWv8Q06f/fVdIQTAH8ezmdgTTQBBJJWGbYftzBn3l9UHchuZ1q0hBPlDf8PXPapEoMTNWtA/U9skb4Lh14ZDcm8ZVD8zKgP46pnnjUEpLpAJZsVo+jsv18+FHjO+no8gLT5PD/2FcUwuZmKXYqoLz8sBMF+2U1gahvrekWDQVx2x1vZeqvVqdrHrL/jzYb+yqeenbHExOiRQBrYveqN2yPzUIvzVOVjvalFFcRjeKzF2sSHdPTlrU9YVqB26dP/2nIWkl+7KGzyZfxlmdn/XVRli6Akzpfw6JMgdSnETNKgdFIV/dQIDAQAB"
	zfb          = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+CNfnlKghbwFIby49+xLDeIh4inp0ljwc/qK8Tm2WQ5ybcTIg8p1P3tvb0TRWyta3nMhcmTkcv2N+87bod3vJ/UhMD7RizLdjyARcEUk7sasLojCotuqShsSDCjmUGyHd007K6S9qT+INdXq3TBolkFe6Z9/DCYGvd43ir24jdXrhrgO/Dx8Pk3k4isxLk20t4os6i7tow51DYQUg4Ajxskfpevotpjnyvgz30jEqcRigHKEVAuxAmS3iBSI6hVWQaPzaT4p/XH6UJ8mWZfNUkKem91483c06NMooHg5VqAT6GE7Z3d3j0a8zJ5GLblgr03iC5cYW+2h+5EnP+3/QIDAQAB"
	yysiyao      = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCDPytEYVya9Fnwxlm/i3EGtqarJ5SMYPhYI0xBa/xDTp/99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ori6H1NmH0DM0VltU7UnUSuqMBC/sQaeM0cXFItOPZ/B5qoz9I4/VdmjNl8ir7b9JFyfMuCGnzQKBgAR/JQSoQWYRpCA7cslSwk8XoJucwK8QaIi0EUnmL5HkKE3vYwsFAQgw/ftUM4hPDOxoc6wsg3Eb+6S8FM5tesN2CbsyLZ5oTlpX0PXqe5blmpr0M+r2rG3/oeiYfQoIJTXlQK17mfTlq5/P5YtbC89xHeNfJBzeRfhxuLC7tATnAoGAfMj1sgBnbonKLJmNAf9x2Iv0tItE860FyGjb11pQqtN7BCo7fy2vJtxbZtxBcvqauvd9n4SnFgf7Wmji80RPIX04qwHyfxdODbq9heri9jhpCBPGzOdu66/8K1sGMFCX/F5FDmxIkARooqCuULVSKhzhCriG29p/oZQAYBOf09Q="
	AES          = "S7U2TyL6zIvRXR0Y7bZ0+A=="
	isProduction = true
)

type BuydaibiBody struct {
	Uid       int64  `json:"uid" gorm:"uid"`
	Packageid int64  `json:"packageid" gorm:"packageid"`
	Qudao     string `json:"qudao" gorm:"qudao"`
}

func Buydaibialipay(ctx *gin.Context) {
	request := BuydaibiBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	packageid := request.Packageid
	if uid == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    101,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请登录",
		})
		return
	}
	var packageinfo models.Package
	data_source.Db.Where("id = ?", packageid).First(&packageinfo)
	orderno := Generateto(time.Time{})

	buy := models.Buydaibi{
		Uid:       uid,
		Packageid: packageid,
		Addtime:   time.Now().Unix(),
		Status:    1,
		Orderno:   orderno,
	}
	data_source.Db.Create(&buy)

	client, err := alipay.NewClient(appidzfb, yysiyao, true)
	if err != nil {
		xlog.Error(err)
		return
	}

	// 打开Debug开关，输出日志，默认关闭
	client.DebugSwitch = gopay.DebugOn

	// 设置支付宝请求 公共参数
	//    注意：具体设置哪些参数，根据不同的方法而不同，此处列举出所有设置参数
	client.SetLocation(alipay.LocationShanghai). // 设置时区，不设置或出错均为默认服务器时间
							SetCharset(alipay.UTF8).  // 设置字符编码，不设置默认 utf-8
							SetSignType(alipay.RSA2). // 设置签名类型，不设置默认 RSA2
							SetNotifyUrl("https://chaowan.weizi000.cn/user/alipayNotify")

	// 设置biz_content加密KEY，设置此参数默认开启加密
	//client.SetAESKey("7WfN4bn4FScCWwb2CxmQ2m8MGEMNYpRZ")
	bm := make(gopay.BodyMap)
	bm.Set("subject", "商品购买").
		Set("product_code", "QUICK_MSECURITY_PAY").
		Set("out_trade_no", orderno).
		Set("total_amount", packageinfo.Price*100).
		Set("op_app_id", appidzfb)

	aliRsp, err := client.TradeAppPay(ctx, bm)
	//fmt.Println(aliRsp)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    aliRsp,
	})
	return

}

// 支付宝支付回调
func AlipayNotify(c *gin.Context) {
	notifyReq, err := alipay.ParseNotifyToBodyMap(c.Request) // c.Request 是 gin 框架的写法
	if err != nil {
		xlog.Error(err)
		return
	}
	ok, err := alipay.VerifySign(yygongyao, notifyReq)
	if err != nil {
		xlog.Error(err)
		return
	}
	fmt.Println(notifyReq)
	fmt.Println(ok)
	//Zhifupaydaibi()
	c.String(http.StatusOK, "%s", "success")
	return
}

func Generateto(t time.Time) string {
	// 生成当前日期部分（例如：20231008）
	datePart := time.Now().UnixNano()
	// 生成随机数部分（4位随机数）
	rand.Seed(time.Now().UnixNano())
	randomPart := fmt.Sprintf("%04d", rand.Intn(10000))
	// 最终的订单号由前缀、日期和随机数部分组成
	orderNumber := utils.Int64string(datePart) + randomPart
	return orderNumber
}

func Goodalipay(orderno string, price int64) (data string) {
	ctx := context.Background()
	client, err := alipay.NewClient(appidzfb, yysiyao, true)
	if err != nil {
		xlog.Error(err)
		return
	}

	// 打开Debug开关，输出日志，默认关闭
	client.DebugSwitch = gopay.DebugOn

	// 设置支付宝请求 公共参数
	//    注意：具体设置哪些参数，根据不同的方法而不同，此处列举出所有设置参数
	client.SetLocation(alipay.LocationShanghai). // 设置时区，不设置或出错均为默认服务器时间
							SetCharset(alipay.UTF8).  // 设置字符编码，不设置默认 utf-8
							SetSignType(alipay.RSA2). // 设置签名类型，不设置默认 RSA2
							SetNotifyUrl("https://chaowan.weizi000.cn/user/alipayNotify")

	// 设置biz_content加密KEY，设置此参数默认开启加密
	//client.SetAESKey("7WfN4bn4FScCWwb2CxmQ2m8MGEMNYpRZ")
	bm := make(gopay.BodyMap)
	bm.Set("subject", "商品购买").
		Set("product_code", "QUICK_MSECURITY_PAY").
		Set("out_trade_no", orderno).
		Set("total_amount", price).
		Set("op_app_id", appidzfb)

	aliRsp, err := client.TradeAppPay(ctx, bm)
	return aliRsp

}
